package com.gitee.wsl.mathematics.geometry.d2.curve.equation

import com.gitee.wsl.mathematics.coordinate.d2.Coordinate2
import com.gitee.wsl.mathematics.coordinate.d2.Point2D
import com.gitee.wsl.mathematics.vector.ext.mid
import kotlin.math.pow

object ControlPointGenerator {

    fun quadraticEquationControlPoint(
        startPoint: Point2D,
        endPoint: Point2D,
        equation: QuadraticEquation
    ): Point2D {
        var controlPoint = startPoint.mid(endPoint)

        if (equation.a != 0.0) {
            val m1 = equation.a * 2 * startPoint.x + equation.b
            val m2 = equation.a * 2 * endPoint.x + equation.b

            val linearEquation1 = LinearEquation(m1, startPoint.y - startPoint.x * m1)
            val linearEquation2 = LinearEquation(m2, endPoint.y - endPoint.x * m2)

            val x = (linearEquation1.b - linearEquation2.b) / (linearEquation2.a - linearEquation1.a)
            val y = linearEquation1.a * x + linearEquation1.b

            controlPoint = startPoint.create(x, y) as Point2D
        }

        return controlPoint
    }

    private fun getX(sp: Point2D, ep: Point2D, e: QuadraticEquation): Double {
        return (ep.y - sp.y + 2 * e.a * (sp.x.pow(2.0) - ep.x.pow(2.0)) + e.b * (sp.x - ep.x)) / (2 * e.a * (sp.x - ep.x))
    }

    private fun getY(sp: Point2D, ep: Point2D, e: QuadraticEquation): Double {
        return (2 * e.a * sp.x + e.b) * (getX(sp, ep, e) - sp.x) + sp.y
    }
}
